package com.bigdata.schaduler.tasks;

import cn.hutool.json.JSONUtil;
import org.apache.dolphinscheduler.plugin.task.api.*;
import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus;
import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;


/**
 * init -> handle -> （getExistStatus） alter(sendResult to master) -> 异常（getExistStatus）cancel
 */
public class UdtTask extends AbstractTask {

  private UdtTaskParameters taskParameters;
  private final TaskExecutionContext taskExecutionContext;

  public UdtTask(TaskExecutionContext taskExecutionContext) {
    super(taskExecutionContext);
    this.taskExecutionContext = taskExecutionContext;
  }

  @Override
  public void init() {
    this.taskParameters = JSONUtil.toBean(taskExecutionContext.getTaskParams(), UdtTaskParameters.class, true);
  }

  @Override
  public void handle(TaskCallBack taskCallBack) throws TaskException {
    // 自定义http请求 发送到UdtTaskParameters.httpCallbackUrl执行真正的任务
    // 获取结果更新 exitStatusCode，海豚会调用getExitStatusCode()发送状态到master、发送alter等
  }

  @Override
  public void cancel() throws TaskException {

  }

  @Override
  public AbstractParameters getParameters() {
    return this.taskParameters;
  }

  @Override
  public TaskExecutionStatus getExitStatus() {
    TaskExecutionStatus status;
    switch (getExitStatusCode()) {
      case TaskConstants.EXIT_CODE_SUCCESS:
        status = TaskExecutionStatus.SUCCESS;
        break;
      case TaskConstants.RUNNING_CODE:
        status = TaskExecutionStatus.RUNNING_EXECUTION;
        break;
      case TaskConstants.EXIT_CODE_KILL:
        status = TaskExecutionStatus.KILL;
        break;
      default:
        status = TaskExecutionStatus.FAILURE;
        break;
    }
    return status;
  }
}
